const {
	Backend,
	Joi
} = require('dx-router-admin');

module.exports = class Menu extends Backend {
	constructor(ctx) {
		super(ctx);
		this.multiFields = [];
		this.dto = {
			name: Joi.string().required().error(new Error('标签名称不能为空'))
		};
	}
	async index(where) {
		const {
			$dx
		} = this;
		//查询
		let list = await this.currentService.where(where).order('sort', 'desc').limit(1000).select(true);
		if (list.length === 1000) {
			let listTwo = await this.currentService
				.where(where)
				.where('create_date', '>', list[999].create_date)
				.order('sort', 'desc')
				.limit(1000)
				.select(true);
			list = [...list, ...listTwo];
		}
		return $dx.success($dx.$t(''), list);
	}
	//获取数据
	async list(where) {
		const {
			$dx
		} = this;
		//查询
		let list = await this.currentService.where(where).order('sort', 'desc').limit(1000)
			.select(true);
		if (list.length === 1000) {
			let result = await this.currentService
				.where(where)
				.order('sort', 'desc')
				.skip(1000)
				.limit(1000)
				.select(true);
			list = [...list, ...result];
		}
		if (list.length === 2000) {
			let result = await this.currentService
				.where(where)
				.order('sort', 'desc')
				.skip(2000)
				.limit(1000)
				.select(true);
			list = [...list, ...result];
		}
		if (list.length === 3000) {
			let result = await this.currentService
				.where(where)
				.order('sort', 'desc')
				.skip(3000)
				.limit(1000)
				.select(true);
			list = [...list, ...result];
		}
		if (list.length === 4000) {
			let result = await this.currentService
				.where(where)
				.order('sort', 'desc')
				.skip(4000)
				.limit(1000)
				.select(true);
			list = [...list, ...result];
		}
		if (list.length === 5000) {
			let result = await this.currentService
				.where(where)
				.order('sort', 'desc')
				.skip(5000)
				.limit(1000)
				.select(true);
			list = [...list, ...result];
		}
		//返回数据
		return $dx.success($dx.$t(''), list);
	}
	// 存在则更新，不存在则新增
	async save(data) {
		if (this.dto !== null) {
			const schema = Joi.object(this.dto);
			const {
				error
			} = schema.validate(data, {
				// false：表示对所有字段进行校验错误；如果不定义，只要发现不合法的字段就会停止校验
				abortEarly: this.abortEarly,
				// 允许验证被对象包含没有定义校验规则的未知字段，否则会认为被校验数据不通过
				allowUnknown: this.allowUnknown,
			});
			if (error) {
				return this.$dx.fail(error.message);
			}
		}
		const result = await this.currentService.insert(data);
		return this.$dx.success(this.$dx.$t('操作成功'), result);
	}
};